/**
 * 打印组件，调用ECP2.0打印 实现方式： 在顶层窗口创建IFRAME，嵌入2.0空白页面，将IFRAME全屏显示，背景透明
 * 
 * @auther pengxiao
 * @date 2015-11-02
 */
define(["jquery","ecp.pagemessage","jquery.cookie"], function($,$message) {

	function getTopWindow() {
		var container = window;
		while (true) {
			var parent = container.parent;
			if (parent === container) {
				break;
			}
			container = container.parent;
		}
		return container;
	}

	var printUtil = {
		/**
		 * 显示打印窗口.
		 */
		showPrint : function(options) {
			var wTop;
			try {
				wTop = getTopWindow();
			} catch (e) {
				window.console && typeof(window.console.error) === "function" && window.console.error("跨域访问错误。");
				wTop = window;
			}
			if (wTop) {
				var doc = wTop.document;
				var printFrame = doc.getElementById("ecp_print_iframe_3");
				if (!printFrame) {
					printFrame = doc.createElement("iframe");
					printFrame.id = "ecp_print_iframe_3";
					doc.body.appendChild(printFrame);
				}
		        var maxZ = Math.max.apply(null, $.map($('div', $(doc)), function (e, n) {
		        	var pos = $(e).css('position');
		            if ( pos == 'absolute' || pos == 'fixed')
		                return parseInt($(e).css('z-index')) || 1;
		            })
		        );
		        var url = "/grm/ecp/webcore/components/print/printBlank.html";
				if (options) {
					url += "?printOpt=" + encodeURI($.toJSON(options));
				}
				document.body.style.overflow = "hidden";
				printFrame.style["z-index"] = maxZ + 1;
				printFrame.style.top = "0px";
				printFrame.style.left = "0px";
				printFrame.style.width = doc.body.clientWidth + "px";
				printFrame.style.height = '100%';
				printFrame.style.position = "absolute";
				printFrame.style.display = "block";
				printFrame.ALLOWTRANSPARENCY = "true";
				printFrame.src = url;
				//865256  加该参数以便加载南网新UI样式 by zxw
				var pc = printFrame.contentDocument;
				if(pc && pc.body && pc.body.setAttribute){
					pc.body.setAttribute("webversion",3);
				}
				wTop.scrollTo(0,0);
			}
			if (window.printInterVal != null) {
				window.printInterVal = null;
			}
			var _this = this;
			window.printInterVal = setInterval(function() {
				var isHide = $.cookie("hideprint");
				if (isHide == "1") {
					_this.hidePrint();
					window.printInterVal = null;
					document.cookie = "hideprint=0;path=/";
					document.body.style.overflow = "auto";
				}
			}, 1000);
		},
		/**
		 * 隐藏打印窗口.
		 */
		hidePrint : function() {
			var wTop;
			try {
				wTop = getTopWindow();
			} catch (e) {
				window.console && typeof(window.console.error) === "function" && window.console.error("跨域访问错误。");
				wTop = window;
			}
			if (wTop) {
				var doc = wTop.document;
				var printFrame = doc.getElementById("ecp_print_iframe_3");
				if (printFrame) {
					printFrame.style.display = "none";
				}
			}
		}
	};

	return printUtil;
});